package com.hzzftech.watchdog.busi.module.email.service.impl;

import com.hzzftech.watchdog.busi.module.email.service.IEmailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.List;

@Service
public class MailServiceImpl implements IEmailService {
    public static Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);

    //从application.properties配置文件中注入发送者的邮件地址
    @Value("${spring.mail.username}")
    private String fromEmail;

    //注入spring发送邮件的对象
    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public boolean sendAttachMail(String to, String subject, String content) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setTo(to);
        simpleMailMessage.setFrom(fromEmail);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(content);
        try {
            javaMailSender.send(simpleMailMessage);  		//执行发送
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    @Override
    public boolean sendAttachMail(String to, String subject, String content, List<String> filepath) {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content);
            helper.setFrom(fromEmail);
            if(filepath.size()>0){						//读取附件文件（传入文件路径）
                for (String string : filepath) {		//遍历文件数组，实现多个附件的添加
                    FileSystemResource file = new FileSystemResource(string.toString());
                    String fileName = file.getFilename();//获取文件名
                    assert fileName != null;
                    helper.addAttachment(fileName, file);//参数：文件名，文件路径
                }
                try {
                    javaMailSender.send(mimeMessage);		//发送邮件
                } catch (Exception e) {
                    return false;						//发送出现异常(或者文件路径不对)
                }
                return true;							//成功发送
            }else {
                return false;    						//没有附件文件（中断发送）
            }
        } catch (MessagingException e) {
            logger.error("发送邮件失败",e );
            //捕获到创建MimeMessageHelper的异常
			return false;
        }
    }
}
